<template>
  <div class="my-apply-page">
    <!-- 页面标题和统计 -->
    <el-row :gutter="20" class="header-section">
      <el-col :span="24">
        <el-card class="header-card">
          <div class="header-content">
            <div class="title-section">
              <h2>我的异动申请</h2>
              <p class="subtitle">休学、转学、复学、退学申请管理</p>
            </div>
            <div class="stats-section">
              <div class="stat-item">
                <div class="stat-value">{{ applyList.length }}</div>
                <div class="stat-label">总申请数</div>
              </div>
              <div class="stat-divider"></div>
              <div class="stat-item pending">
                <div class="stat-value">{{ pendingCount }}</div>
                <div class="stat-label">待审批</div>
              </div>
              <div class="stat-divider"></div>
              <div class="stat-item success">
                <div class="stat-value">{{ approvedCount }}</div>
                <div class="stat-label">已通过</div>
              </div>
              <div class="stat-divider"></div>
              <div class="stat-item danger">
                <div class="stat-value">{{ rejectedCount }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速申请入口 -->
    <el-card class="quick-apply-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon :size="18"><DocumentAdd /></el-icon>
            <span>快速申请</span>
          </div>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="12" :md="6">
          <div class="apply-item suspension" @click="openApplyDialog('suspension')">
            <div class="apply-icon-wrapper">
              <el-icon :size="48" class="apply-icon"><DocumentRemove /></el-icon>
            </div>
            <div class="apply-name">休学申请</div>
            <div class="apply-desc">因病或其他原因需要暂时离校</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6">
          <div class="apply-item transfer" @click="openApplyDialog('transfer')">
            <div class="apply-icon-wrapper">
              <el-icon :size="48" class="apply-icon"><Switch /></el-icon>
            </div>
            <div class="apply-name">转学申请</div>
            <div class="apply-desc">申请转班或转院系</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6">
          <div class="apply-item return" @click="openApplyDialog('return')">
            <div class="apply-icon-wrapper">
              <el-icon :size="48" class="apply-icon"><CircleCheck /></el-icon>
            </div>
            <div class="apply-name">复学申请</div>
            <div class="apply-desc">休学期满申请恢复学籍</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6">
          <div class="apply-item dropout" @click="openApplyDialog('dropout')">
            <div class="apply-icon-wrapper">
              <el-icon :size="48" class="apply-icon"><CircleClose /></el-icon>
            </div>
            <div class="apply-name">退学申请</div>
            <div class="apply-desc">申请退出学籍</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 我的申请列表 -->
    <el-card class="apply-list-card">
      <template #header>
        <div class="card-header">
          <span>我的申请记录</span>
          <el-button type="primary" size="small" @click="loadMyApplies">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </template>

      <!-- 筛选 -->
      <el-form :inline="true" class="filter-form">
        <el-form-item label="申请类型">
          <el-select 
            v-model="filterSubType" 
            placeholder="全部" 
            clearable 
            style="width: 150px"
            @change="loadMyApplies"
          >
            <el-option label="休学申请" value="suspension" />
            <el-option label="转学申请" value="transfer" />
            <el-option label="复学申请" value="return" />
            <el-option label="退学申请" value="dropout" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="filterStatus" 
            placeholder="全部" 
            clearable 
            style="width: 120px"
            @change="loadMyApplies"
          >
            <el-option label="待审批" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadMyApplies" :icon="Refresh">
            查询
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 申请列表 -->
      <el-table 
        :data="applyList" 
        v-loading="loading"
        stripe
      >
        <el-table-column prop="id" label="申请编号" width="100" />
        <el-table-column prop="subTypeName" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getApplyTypeColor(row.subType)">
              {{ row.subTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="申请内容" show-overflow-tooltip />
        <el-table-column prop="attachmentCount" label="附件" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.attachmentCount > 0" type="info" size="small">
              <el-icon><Paperclip /></el-icon>
              {{ row.attachmentCount }}
            </el-tag>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="approvalLevelName" label="当前层级" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row.id)" link>
              查看详情
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              type="danger" 
              size="small" 
              @click="cancelApply(row.id)"
              link
            >
              撤回
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="loadMyApplies"
        @size-change="loadMyApplies"
        class="pagination"
      />
    </el-card>

    <!-- 申请对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      :title="getApplyDialogTitle()"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="120px">
        <el-alert 
          :title="getApplyTips()" 
          type="info" 
          :closable="false"
          style="margin-bottom: 20px"
        />

        <!-- 休学申请特有字段 -->
        <template v-if="applyForm.subType === 'suspension'">
          <el-form-item label="休学起止时间" prop="dateRange">
            <el-date-picker
              v-model="applyForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </template>

        <!-- 转学申请特有字段 -->
        <template v-if="applyForm.subType === 'transfer'">
          <el-form-item label="目标院系" prop="targetDeptId">
            <el-select 
              v-model="applyForm.targetDeptId" 
              placeholder="请选择院系" 
              clearable
              filterable
              @change="handleDeptChange"
            >
              <el-option
                v-for="dept in deptList"
                :key="dept.id"
                :label="dept.deptName"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目标班级" prop="targetClassId">
            <el-select 
              v-model="applyForm.targetClassId" 
              placeholder="请选择班级" 
              clearable
              filterable
              :disabled="!applyForm.targetDeptId"
            >
              <el-option
                v-for="cls in classList"
                :key="cls.id"
                :label="cls.className"
                :value="cls.id"
              />
            </el-select>
          </el-form-item>
        </template>

        <!-- 申请理由 -->
        <el-form-item label="申请理由" prop="content" required>
          <el-input
            v-model="applyForm.content"
            type="textarea"
            :rows="5"
            placeholder="请详细说明申请理由..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item label="证明材料">
          <FileUpload
            ref="fileUploadRef"
            :file-type="getFileType()"
            category="approval"
            :approval-required="1"
            :multiple="true"
            :limit="5"
            :button-text="'上传' + getFileTypeName()"
            :tip-text="'请上传相关证明材料，支持PDF和图片格式，单个文件不超过10MB'"
            @success="handleFileUploadSuccess"
          />
        </el-form-item>

        <!-- 优先级 -->
        <el-form-item label="紧急程度" prop="priority">
          <el-radio-group v-model="applyForm.priority">
            <el-radio :label="0">普通</el-radio>
            <el-radio :label="1">重要</el-radio>
            <el-radio :label="2">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApply" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="900px"
    >
      <ApprovalDetail v-if="currentApprovalId" :approval-id="currentApprovalId" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DocumentRemove, 
  Switch,
  CircleCheck, 
  CircleClose,
  Refresh,
  DocumentAdd,
  Paperclip
} from '@element-plus/icons-vue'
import FileUpload from '@/components/FileUpload.vue'
import ApprovalDetail from './components/ApprovalDetail.vue'
import { submitStudentApply, getMyApplies, cancelApproval } from '@/api/approval'
import { getDeptList } from '@/api/dept'
import { getClassList } from '@/api/class'

const route = useRoute()

// 申请列表
const loading = ref(false)
const applyList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filterSubType = ref('')
const filterStatus = ref<number | null>(null)

// 统计数据
const pendingCount = computed(() => applyList.value.filter(item => item.status === 0).length)
const approvedCount = computed(() => applyList.value.filter(item => item.status === 1).length)
const rejectedCount = computed(() => applyList.value.filter(item => item.status === 2).length)

// 申请对话框
const applyDialogVisible = ref(false)
const applyFormRef = ref()
const fileUploadRef = ref()
const submitting = ref(false)

const applyForm = reactive({
  // ❌ 不需要studentId字段，后端会自动处理
  // studentId: 0,
  subType: '' as 'suspension' | 'transfer' | 'return' | 'dropout',
  content: '',
  attachmentIds: '',
  targetClassId: undefined as number | undefined,
  targetDeptId: undefined as number | undefined,
  startDate: undefined as string | undefined,
  endDate: undefined as string | undefined,
  priority: 0,
  dateRange: [] as string[]  // 休学起止时间（用于表单验证）
})

const applyRules = {
  content: [
    { required: true, message: '请填写申请理由', trigger: 'blur' },
    { min: 10, message: '申请理由至少10个字', trigger: 'blur' }
  ],
  dateRange: [
    { 
      required: true, 
      message: '请选择休学起止时间', 
      trigger: 'change',
      validator: (_rule: any, value: any, callback: any) => {
        if (!value || value.length !== 2) {
          callback(new Error('请选择休学起止时间'))
        } else {
          callback()
        }
      }
    }
  ],
  targetDeptId: [
    { required: true, message: '请选择目标院系', trigger: 'change' }
  ],
  targetClassId: [
    { required: true, message: '请选择目标班级', trigger: 'change' }
  ]
}

// 院系班级数据
const deptList = ref<any[]>([])
const classList = ref<any[]>([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentApprovalId = ref(0)

/**
 * 加载我的申请列表
 */
const loadMyApplies = async () => {
  loading.value = true
  try {
    const data = await getMyApplies({
      current: currentPage.value,
      size: pageSize.value,
      subType: filterSubType.value || undefined,
      status: filterStatus.value !== null ? filterStatus.value : undefined
    }) as any
    
    if (data) {
      applyList.value = data.records || []
      total.value = data.total || 0
    } else {
      applyList.value = []
      total.value = 0
    }
  } catch (error: any) {
    console.error('加载申请列表失败', error)
    ElMessage.error(error?.message || '加载失败，请检查是否已创建学生档案')
    applyList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/**
 * 打开申请对话框
 */
const openApplyDialog = async (subType: string) => {
  // 重置表单
  applyForm.subType = subType as any
  applyForm.content = ''
  applyForm.attachmentIds = ''
  applyForm.targetClassId = undefined
  applyForm.targetDeptId = undefined
  applyForm.startDate = undefined
  applyForm.endDate = undefined
  applyForm.priority = 0
  applyForm.dateRange = []
  
  // 清空院系班级列表
  deptList.value = []
  classList.value = []
  
  // 如果是转学申请，加载院系数据
  if (subType === 'transfer') {
    applyDialogVisible.value = true // 先打开对话框
    await loadDeptList() // 然后加载数据
  } else {
    applyDialogVisible.value = true
  }
}

/**
 * 加载院系列表
 */
const loadDeptList = async () => {
  try {
    const data = await getDeptList() as any
    console.log('加载院系列表：', data)
    deptList.value = data || []
  } catch (error) {
    console.error('加载院系列表失败', error)
    ElMessage.error('加载院系列表失败')
  }
}

/**
 * 院系改变时加载班级列表
 */
const handleDeptChange = async (deptId: number | undefined) => {
  // 清空班级选择
  applyForm.targetClassId = undefined
  classList.value = []
  
  if (!deptId) {
    return
  }
  
  try {
    const data = await getClassList({ deptId }) as any
    console.log('加载班级列表：', data)
    classList.value = data || []
  } catch (error) {
    console.error('加载班级列表失败', error)
    ElMessage.error('加载班级列表失败')
  }
}

/**
 * 文件上传成功
 */
const handleFileUploadSuccess = (files: any[]) => {
  applyForm.attachmentIds = files.map(f => f.id).join(',')
}

/**
 * 提交申请
 */
const submitApply = async () => {
  if (!applyFormRef.value) return
  
  await applyFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    // 处理日期范围
    if (applyForm.subType === 'suspension' && applyForm.dateRange.length === 2) {
      applyForm.startDate = applyForm.dateRange[0]
      applyForm.endDate = applyForm.dateRange[1]
    }
    
    submitting.value = true
    try {
      await submitStudentApply(applyForm)
      ElMessage.success('申请提交成功！请等待审批')
      applyDialogVisible.value = false
      fileUploadRef.value?.clearFiles()
      loadMyApplies()
    } catch (error) {
      ElMessage.error('提交失败：' + (error as any).message)
    } finally {
      submitting.value = false
    }
  })
}

/**
 * 查看详情
 */
const viewDetail = (id: number) => {
  currentApprovalId.value = id
  detailDialogVisible.value = true
}

/**
 * 撤回申请
 */
const cancelApply = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要撤回此申请吗？撤回后将不能恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await cancelApproval(id)
    ElMessage.success('撤回成功')
    loadMyApplies()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('撤回失败：' + (error.message || '未知错误'))
    }
  }
}

/**
 * 获取对话框标题
 */
const getApplyDialogTitle = () => {
  const titleMap = {
    suspension: '休学申请',
    transfer: '转学申请',
    return: '复学申请',
    dropout: '退学申请'
  }
  return titleMap[applyForm.subType] || '异动申请'
}

/**
 * 获取申请提示
 */
const getApplyTips = () => {
  const tipsMap = {
    suspension: '休学申请需要提供医院开具的诊断证明或其他相关材料',
    transfer: '转学申请需要说明转学原因，并选择目标院系和班级',
    return: '复学申请需要说明休学期间的情况',
    dropout: '退学申请是重大决定，请慎重考虑并详细说明理由'
  }
  return tipsMap[applyForm.subType] || ''
}

/**
 * 获取文件类型
 */
const getFileType = () => {
  const typeMap = {
    suspension: 'medical',
    transfer: 'transfer',
    return: 'academic',
    dropout: 'other'
  }
  return typeMap[applyForm.subType] || 'other'
}

/**
 * 获取文件类型名称
 */
const getFileTypeName = () => {
  const nameMap = {
    suspension: '医疗证明',
    transfer: '转学证明',
    return: '复学材料',
    dropout: '相关材料'
  }
  return nameMap[applyForm.subType] || '附件'
}

/**
 * 获取申请类型颜色
 */
const getApplyTypeColor = (subType: string) => {
  const colorMap: Record<string, any> = {
    suspension: '',
    transfer: 'success',
    return: 'warning',
    dropout: 'danger'
  }
  return colorMap[subType] || ''
}

/**
 * 获取状态颜色
 */
const getStatusColor = (status: number) => {
  const colorMap: Record<number, any> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return colorMap[status] || ''
}

/**
 * 获取状态文本
 */
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待审批',
    1: '已通过',
    2: '已拒绝'
  }
  return textMap[status] || '未知'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dateTime.replace('T', ' ').substring(0, 19)
}

onMounted(async () => {
  await loadMyApplies()
  
  // 检查路由参数，如果有 approvalId，则自动打开详情
  const approvalId = route.query.approvalId
  if (approvalId) {
    currentApprovalId.value = Number(approvalId)
    detailDialogVisible.value = true
  }
})
</script>

<style scoped lang="scss">
.my-apply-page {
  padding: 20px;
  background-color: #f5f7fa;

  .header-section {
    margin-bottom: 20px;
  }

  .header-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 20px;
      
      .title-section {
        h2 {
          margin: 0 0 8px 0;
          font-size: 28px;
          font-weight: 600;
          color: white;
        }

        .subtitle {
          margin: 0;
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
        }
      }

      .stats-section {
        display: flex;
        align-items: center;
        gap: 24px;
        flex-wrap: wrap;

        .stat-item {
          text-align: center;
          padding: 0 12px;

          .stat-value {
            font-size: 32px;
            font-weight: bold;
            color: white;
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 13px;
            color: rgba(255, 255, 255, 0.85);
            white-space: nowrap;
          }

          &.pending .stat-value {
            color: #ffd700;
          }

          &.success .stat-value {
            color: #67c23a;
          }

          &.danger .stat-value {
            color: #ff6b6b;
          }
        }

        .stat-divider {
          width: 1px;
          height: 40px;
          background-color: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }

  .quick-apply-card {
    margin-bottom: 20px;
    border-radius: 12px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .apply-item {
      text-align: center;
      padding: 28px 16px;
      border: 2px solid #e4e7ed;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      margin-bottom: 20px;
      background: white;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, transparent, transparent);
        transition: all 0.3s;
      }

      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
        border-color: transparent;
      }

      &.suspension {
        &::before {
          background: linear-gradient(90deg, #409eff, #66b1ff);
        }
        
        &:hover {
          background: linear-gradient(135deg, #f0f9ff 0%, #e3f2fd 100%);
          border-color: #409eff;
          
          .apply-icon-wrapper {
            background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
            
            .apply-icon {
              color: white;
            }
          }
        }
      }

      &.transfer {
        &::before {
          background: linear-gradient(90deg, #67c23a, #95d475);
        }
        
        &:hover {
          background: linear-gradient(135deg, #f0f9ff 0%, #f1f8f4 100%);
          border-color: #67c23a;
          
          .apply-icon-wrapper {
            background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
            
            .apply-icon {
              color: white;
            }
          }
        }
      }

      &.return {
        &::before {
          background: linear-gradient(90deg, #e6a23c, #f0c78a);
        }
        
        &:hover {
          background: linear-gradient(135deg, #fdf6ec 0%, #fef5e7 100%);
          border-color: #e6a23c;
          
          .apply-icon-wrapper {
            background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
            
            .apply-icon {
              color: white;
            }
          }
        }
      }

      &.dropout {
        &::before {
          background: linear-gradient(90deg, #f56c6c, #f89898);
        }
        
        &:hover {
          background: linear-gradient(135deg, #fef0f0 0%, #fee 100%);
          border-color: #f56c6c;
          
          .apply-icon-wrapper {
            background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
            
            .apply-icon {
              color: white;
            }
          }
        }
      }

      .apply-icon-wrapper {
        width: 72px;
        height: 72px;
        margin: 0 auto 16px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        transition: all 0.3s;

        .apply-icon {
          transition: all 0.3s;
        }
      }

      .apply-name {
        margin: 0 0 8px;
        font-size: 17px;
        font-weight: 600;
        color: #303133;
      }

      .apply-desc {
        font-size: 13px;
        color: #909399;
        line-height: 1.6;
      }
    }
  }

  .apply-list-card {
    border-radius: 12px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .filter-form {
      margin-bottom: 20px;
      padding: 16px;
      background: #f5f7fa;
      border-radius: 8px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    padding: 12px;

    .header-card .header-content {
      flex-direction: column;
      align-items: flex-start;

      .stats-section {
        width: 100%;
        justify-content: space-around;

        .stat-divider {
          display: none;
        }
      }
    }

    .quick-apply-card .apply-item {
      padding: 20px 12px;
      margin-bottom: 12px;

      .apply-icon-wrapper {
        width: 56px;
        height: 56px;

        .apply-icon {
          font-size: 32px;
        }
      }

      .apply-name {
        font-size: 15px;
      }

      .apply-desc {
        font-size: 12px;
      }
    }
  }
}
</style>

